package upbody

import (
	"bytes"
	"encoding/binary"
	"gitee.com/Cookie_XiaoD/go-terminalserver/protocol/std808core"
	"gitee.com/Cookie_XiaoD/go-terminalserver/protocol/std808core/msg"
	"gitee.com/Cookie_XiaoD/go-terminalserver/util"
	"log"
)

func AnalyseReg(revMsg *msg.Std808Msg) *TerminalRegBody {
	if revMsg.MessageID != msg.TerminalReg {
		return nil
	}
	bodyBytes := getRealMsgBody(revMsg)
	//终端注册至少有38个字节
	if len(bodyBytes) < 38 {
		return nil
	}

	r := &TerminalRegBody{}
	reader := bytes.NewReader(bodyBytes)
	var err error
	err = binary.Read(reader, binary.BigEndian, &r.ProvincialID)
	err = binary.Read(reader, binary.BigEndian, &r.CityOrCountyID)
	var mfBytes [5]byte
	err = binary.Read(reader, binary.BigEndian, &mfBytes)
	r.ManufacturerID = string(mfBytes[0:])
	var tmBytes [20]byte
	err = binary.Read(reader, binary.BigEndian, &tmBytes)
	r.TerminalModel = string(tmBytes[0:])
	var tidBytes [7]byte
	err = binary.Read(reader, binary.BigEndian, &tidBytes)
	r.TerminalID = string(tidBytes[0:])
	err = binary.Read(reader, binary.BigEndian, &r.PlateColor)

	vidBytes := bodyBytes[37:]
	r.VehicleID, _ = util.GBK2UTF8String(vidBytes)

	if err != nil {
		return nil
	}

	return r
}

func AnalyseAuth(revMsg *msg.Std808Msg) *TerminalAuthBody {
	if revMsg.MessageID != msg.TerminalAuth {
		return nil
	}
	bodyBytes := getRealMsgBody(revMsg)
	//终端鉴权消息体至少有1个字节
	err := checkMsgLen(bodyBytes, 1, CANNOTLESS, msg.TerminalAuth)
	if err != nil {
		return nil
	}

	r := &TerminalAuthBody{}

	authCode, err := util.GBK2UTF8String(bodyBytes)
	if err != nil {
		return nil
	}
	r.AuthCode = authCode
	return r
}

func AyalyseLocation(revMsg *msg.Std808Msg) *TerminalLocationBody {
	if revMsg.MessageID != msg.TerminalLocation {
		return nil
	}
	bodyBytes := getRealMsgBody(revMsg)
	//不能小于28个字节
	err := checkMsgLen(bodyBytes, 28, CANNOTLESS, msg.TerminalLocation)
	if err != nil {
		return nil
	}
	//TODO:解析定位数据

	return nil
}

func checkMsgLen(bodyBytes []byte, length int, ct checkType, msgid msg.Std808TerminalMsgID) error {
	if bodyBytes == nil {
		return std808core.Error_BodyLenError
	}
	if ct == CANNOTLESS {
		if len(bodyBytes) < length {
			log.Printf("%v消息长度有误,长度过小", msgid)
			return std808core.Error_BodyLenError
		}
	} else {
		if len(bodyBytes) != length {
			log.Printf("%v消息长度有误，长度不等于", msgid)
			return std808core.Error_BodyLenError
		}
	}
	return nil
}

func getRealMsgBody(msg *msg.Std808Msg) []byte {
	if msg.ByRSA {
		//TODO:RSA解密
	}
	return msg.MessageBody
}

type checkType byte

const (
	//不能小于指定长度
	CANNOTLESS checkType = iota
	//长度必须相等
	LENMUSTEQUAL
)
